package com.yylending.las.common.widgets;

import android.content.Context;
import android.content.ContextWrapper;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.support.annotation.ColorRes;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.AppCompatEditText;
import android.text.Editable;
import android.text.TextPaint;
import android.text.TextWatcher;
import android.util.AttributeSet;
import android.view.ActionMode;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.inputmethod.InputMethodManager;
import com.yyfax.common.tools.DensityUtil;
import com.yylending.las.R;

/**
 * 带边框的EditText
 */
public class BorderEditText extends AppCompatEditText implements TextWatcher {

	static String TAG = "BorderEditText";

	private int mFigures;//需要输入的位数
	private float mBorderWidth;//线的宽度

	private OnAuthCodeChangedListener mOnCodeChangedListener;
	private int mEachRectLength = 0;//每个矩形的边长
	private Paint mBottomSelectedPaint;
	private int mBorderColor;
	private int mCurrentPosition = 0;

	public BorderEditText(Context context) {
		this(context, null);
	}

	public BorderEditText(Context context, AttributeSet attrs) {
		this(context, attrs, 0);
	}

	public BorderEditText(Context context, AttributeSet attrs, int defStyleAttr) {
		super(context, attrs, defStyleAttr);
		initAttrs(attrs);
		setBackgroundColor(ContextCompat.getColor(context, android.R.color.transparent));// 去掉系统自带下划线
		initPaint();
		setFocusableInTouchMode(true);
		disableCopyPaste();
		super.addTextChangedListener(this);
	}

	/**
	 * 初始化paint
	 */
	private void initPaint() {
		mBottomSelectedPaint = new Paint();
		mBottomSelectedPaint.setStyle(Paint.Style.STROKE);
		mBottomSelectedPaint.setAntiAlias(true);
		mBottomSelectedPaint.setColor(mBorderColor);
		mBottomSelectedPaint.setStrokeWidth(mBorderWidth);
	}

	/**
	 * 初始化Attrs
	 */
	private void initAttrs(AttributeSet attrs) {
		TypedArray ta = getContext().obtainStyledAttributes(attrs, R.styleable.border_edit_text);
		mFigures = ta.getInteger(R.styleable.border_edit_text_numbers, 6);
		mBorderColor = ta.getColor(R.styleable.border_edit_text_borderColor, getCurrentTextColor());
		mBorderWidth = 1;
		ta.recycle();
	}

	@Override
	protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
		int widthResult = 0, heightResult = 0;
		//最终的宽度
		int widthMode = MeasureSpec.getMode(widthMeasureSpec);
		int widthSize = MeasureSpec.getSize(widthMeasureSpec);
		if (widthMode == MeasureSpec.EXACTLY) {
			widthResult = widthSize;
		} else {
			widthResult = DensityUtil.getInstance(getContext()).getWindowWidth();
		}
		//每个矩形的宽度
		mEachRectLength = (widthResult - (mFigures - 1)) / mFigures;
		Paint paint = getPaint();
		Paint.FontMetrics fontMetrics = paint.getFontMetrics();
		float fontH = fontMetrics.descent - fontMetrics.ascent;
		int viewTotalH = (int) (mBorderWidth + fontH);

		//最终的高度
		int heightMode = MeasureSpec.getMode(heightMeasureSpec);
		int heightSize = MeasureSpec.getSize(heightMeasureSpec);
		if (heightMode == MeasureSpec.EXACTLY) {
			heightResult = heightSize;
		} else {
			heightResult = viewTotalH;
		}
		setMeasuredDimension(widthResult, heightResult);
	}

	@Override
	protected void onDraw(Canvas canvas) {
		int width = mEachRectLength - getPaddingLeft() - getPaddingRight();
		int totalWidth = getMeasuredWidth() - getPaddingLeft() - getPaddingRight();
		int height = getMeasuredHeight() - getPaddingTop() - getPaddingBottom();

		float halfWidth = 0.5f;
		canvas.drawRect(halfWidth, halfWidth, totalWidth - halfWidth, height - halfWidth, mBottomSelectedPaint);

		String value = getText().toString();
		for (int i = 0; i < value.length(); i++) {
			canvas.save();
			int start = width * i + (i + 1);
			float x = start + width / 2;
			TextPaint paint = getPaint();
			paint.setTextAlign(Paint.Align.CENTER);
			paint.setColor(getCurrentTextColor());
			Paint.FontMetrics fontMetrics = paint.getFontMetrics();
			float baseline = (height - fontMetrics.bottom + fontMetrics.top) / 2 - fontMetrics.top;
			//float baseline = height - mBorderWidth - mBottomLineMarginTop;
			canvas.drawText(String.valueOf(value.charAt(i)), x, baseline, paint);
			canvas.restore();
		}

		for (int i = 1; i < mFigures; i++) {
			int lineX = width * i + i;
			canvas.drawLine(lineX, 1, lineX, height - 1, mBottomSelectedPaint);
		}
	}

	@Override
	public void beforeTextChanged(CharSequence s, int start, int count, int after) {
		mCurrentPosition = getText().length();
		postInvalidate();
	}

	@Override
	public void onTextChanged(CharSequence s, int start, int before, int count) {
		mCurrentPosition = getText().length();
		postInvalidate();
		if (mOnCodeChangedListener != null) {
			mOnCodeChangedListener.onAuthCodeChanged(getText(), start, before, count);
		}
	}

	@Override
	public void afterTextChanged(Editable s) {
		mCurrentPosition = getText().length();
		postInvalidate();
		if (getText().length() == mFigures) {
			if (mOnCodeChangedListener != null) {
				mOnCodeChangedListener.onInputCompleted(getText());
			}
		} else if (getText().length() > mFigures) {
			getText().delete(mFigures, getText().length());
		}
	}

	/**
	 * 处理EditText双击会出现选中以及知识标识的问题.
	 *
	 * @param event
	 * @return
	 */
	@Override
	public boolean onTouchEvent(MotionEvent event) {
		switch (event.getAction()) {
			case MotionEvent.ACTION_DOWN:
				InputMethodManager imm = (InputMethodManager) (((((ContextWrapper) getContext()).getBaseContext()))
						.getSystemService(Context.INPUT_METHOD_SERVICE));
				imm.showSoftInput(this, InputMethodManager.SHOW_IMPLICIT);
				return true;
			case MotionEvent.ACTION_UP:
				return true;
			default:
				break;
		}

		return super.onTouchEvent(event);
	}


	/**
	 * 返回颜色
	 */
	private int getColor(@ColorRes int color) {
		return ContextCompat.getColor(getContext(), color);
	}

	private void disableCopyPaste() {
		setLongClickable(false);
		setTextIsSelectable(false);
		setSelectAllOnFocus(false);
		setSelected(false);
		setCustomSelectionActionModeCallback(new ActionMode.Callback() {
			@Override
			public boolean onCreateActionMode(ActionMode mode, Menu menu) {
				return false;
			}

			@Override
			public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
				return false;
			}

			@Override
			public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
				return false;
			}

			@Override
			public void onDestroyActionMode(ActionMode mode) {

			}
		});
	}

	public void setFigures(int figures) {
		mFigures = figures;
		postInvalidate();
	}

	public void setBottomLineHeight(int bottomLineHeight) {
		this.mBorderWidth = bottomLineHeight;
		postInvalidate();
	}

	public void setOnAuthCodeChangedListener(OnAuthCodeChangedListener listener) {
		this.mOnCodeChangedListener = listener;
	}

	public interface OnAuthCodeChangedListener {
		void onAuthCodeChanged(CharSequence s, int start, int before, int count);

		void onInputCompleted(CharSequence s);
	}

	public void setReadOnly(boolean readOnly){
		setCursorVisible(!readOnly);      //设置输入框中的光标不可见
		setFocusable(!readOnly);           //无焦点
		setFocusableInTouchMode(!readOnly);     //触摸时也得不到焦点
	}
}